package com.byzk.p2p.admin.user.controller;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.jsoup.helper.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.byzk.p2p.admin.bank.service.BankCardService;
import com.byzk.p2p.admin.base.controller.AdminBaseController;
import com.byzk.p2p.admin.base.util.DateUtils;
import com.byzk.p2p.admin.base.util.JsonMsg;
import com.byzk.p2p.admin.base.util.PageInfo;
import com.byzk.p2p.admin.base.util.RequestUtil;
import com.byzk.p2p.admin.base.util.SHA;
import com.byzk.p2p.admin.user.dto.InviteRef;
import com.byzk.p2p.admin.user.dto.User;
import com.byzk.p2p.admin.user.dto.UserAccount;
import com.byzk.p2p.admin.user.service.UserAccountService;
import com.byzk.p2p.admin.user.service.UserAuthService;
import com.byzk.p2p.admin.user.service.UserService;
import com.byzk.p2p.admin.user.vo.InviteRefVo;
import com.byzk.p2p.front.service.FrontUserService;

@RequestMapping("/admin/user")
@Controller
public class UserController extends AdminBaseController {

	@Autowired
	private UserService userService;
	@Autowired
	private UserAccountService accountService;
	@Autowired
	private FrontUserService frontUserService;
	@Autowired
	private UserAuthService userAuthService;
	@Autowired
	private BankCardService bankCardService;
	
	/**
	 * 分页实现
	 * @param model 视图对象
	 * @param index 当前页数
	 * @param limit 每页显示条数
	 * @param username 用户名
	 * @param realname 真实姓名
	 * @param phone 手机号
	 * @param regTimeFrom 注册时间开始
	 * @param regTimeTo 注册时间结束
	 * @param invitedUsername 受邀用户名
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/list")
	public String listView(Model model,
						   @RequestParam(value="index",required=false,defaultValue="1") int index,
						   @RequestParam(value="limit",required=false,defaultValue="10") int limit,
						   @RequestParam(value="username",required=false) String username,
						   @RequestParam(value="phone",required=false) String phone,
						   @RequestParam(value="regTimeFrom",required=false) String regTimeFrom,
						   @RequestParam(value="regTimeTo",required=false) String regTimeTo,
						   @RequestParam(value="invitedUsername",required=false) String invitedUsername)throws Exception{
		Map<String, Object> queryMap = new HashMap<String, Object>();
		
		if (StringUtils.isNotBlank(username)) {
			username=java.net.URLDecoder.decode(username , "UTF-8");
			queryMap.put("matchUser", username);
			model.addAttribute("username", username);
		}
		if (StringUtils.isNotBlank(regTimeFrom)) {
			queryMap.put("regTimeFrom",DateUtils.getRealDate(DateUtils.convert(regTimeFrom, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
			model.addAttribute("regTimeFrom", regTimeFrom);
		}
		if (StringUtils.isNotBlank(regTimeTo)) {
			queryMap.put("regTimeTo", DateUtils.getFullDate(DateUtils.convert(regTimeTo, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
			model.addAttribute("regTimeTo", regTimeTo);
		}
		if (StringUtils.isNotBlank(invitedUsername)) {
			invitedUsername=java.net.URLDecoder.decode(invitedUsername , "UTF-8");
			queryMap.put("invitedUsername",invitedUsername);
			model.addAttribute("invitedUsername", invitedUsername);
		}
		PageInfo<User> pageInfo=userService.listAll(queryMap,index,limit);
		model.addAttribute("pageInfo", pageInfo);
		return ftl(Thread.currentThread().getStackTrace());
	}
	
	/**
	 * 分页查询邀请用户
	 * @param model 视图对象
	 * @param index 当前页数
	 * @param limit 每页显示条数
	 * @param invitedUsername 邀请用户名
	 * @param invitedUserType 邀请用户类型
	 * @param userOperateType 受邀用户操作类型
	 * @param username 受邀请用户名
	 * @return
	 */
	@RequestMapping(value="/listInviteUser")
	public String listInviteUser(Model model,
						   @RequestParam(value="index",required=false,defaultValue="1") int index,
						   @RequestParam(value="limit",required=false,defaultValue="10") int limit,
						   @RequestParam(value="invitedUsername",required=false) String invitedUsername,
						   @RequestParam(value="username",required=false)String username,
						   @RequestParam(value="invitedUserType",required=false)Integer invitedUserType,
						   @RequestParam(value="userOperateType",required=false)Integer userOperateType)throws ParseException{
		InviteRefVo inviteRefVo = new InviteRefVo();
		inviteRefVo.setIndex(index);
		inviteRefVo.setLimit(limit);
		if (StringUtils.isNotBlank(invitedUsername)) {
			inviteRefVo.setMatchInvitedUsername(invitedUsername);
			model.addAttribute("invitedUsername", invitedUsername);
		}
		if (StringUtils.isNotBlank(username)) {
			inviteRefVo.setMatchUsername(username);
			model.addAttribute("username", username);
		}
		if (invitedUserType != null) {
			inviteRefVo.setInvitedUserType(invitedUserType);
			model.addAttribute("invitedUserType", invitedUserType);
		}
		if (userOperateType != null) {
			inviteRefVo.setUserOperateType(userOperateType);
			model.addAttribute("userOperateType", userOperateType);
		}
		PageInfo<InviteRefVo> pageInfo=userService.listInviteRef(inviteRefVo);
		model.addAttribute("pageInfo", pageInfo);
		return ftl(Thread.currentThread().getStackTrace());
	}
	
	
	/**
	 * 分页查询用户邀请排名
	 * @param model 视图对象
	 * @param index 当前页数
	 * @param limit 每页显示条数
	 * @param invitedUserType 邀请用户类型
	 * @param userOperateType 受邀用户操作类型
	 * @return
	 */
	@RequestMapping(value="/listInviteUser/rank")
	public String listInviteUserRank(Model model,
						   @RequestParam(value="index",required=false,defaultValue="1") int index,
						   @RequestParam(value="limit",required=false,defaultValue="10") int limit,
						   @RequestParam(value="invitedUserType",required=false)Integer invitedUserType,
						   @RequestParam(value="userOperateType",required=false)Integer userOperateType)throws ParseException{
		InviteRefVo inviteRefVo = new InviteRefVo();
		inviteRefVo.setIndex(index);
		inviteRefVo.setLimit(limit);
		if (invitedUserType != null) {
			inviteRefVo.setInvitedUserType(invitedUserType);
			model.addAttribute("invitedUserType", invitedUserType);
		}
		if (userOperateType != null) {
			inviteRefVo.setUserOperateType(userOperateType);
			model.addAttribute("userOperateType", userOperateType);
		}
		PageInfo<InviteRefVo> pageInfo=userService.listInviteUserRank(inviteRefVo);
		model.addAttribute("pageInfo", pageInfo);
		return ftl(Thread.currentThread().getStackTrace());
	}
	
	@RequestMapping(value="/update")
	public String addView(){
		return ftl(Thread.currentThread().getStackTrace());
	}
	
	/**
	 * 后台手动注册用户
	 * @return
	 */
	@RequestMapping(value="/update",method=RequestMethod.POST)
	@ResponseBody
	public String addUser(@RequestBody User dto){
		try {
			if(StringUtil.isBlank(dto.getUsername())){
				super.printJSON(new JsonMsg(1, "用户名不能为空",null));
				return null;
			}else{
				User temp=new User();
				temp.setUsername(dto.getUsername());
				List<User> u=userService.getByUser(temp);
				if(u.size()>0){
					super.printJSON(new JsonMsg(4, "用户名已被注册",null));
					return null;
				}
			}
			
			if(StringUtil.isBlank(dto.getPhone())){
				super.printJSON(new JsonMsg(2, "手机号不能为空",null));
				return null;
			}else{
				User temp=new User();
				temp.setPhone(dto.getPhone());
				List<User> u=userService.getByUser(temp);	
				if(u.size()>0){
					super.printJSON(new JsonMsg(5, "手机号已被注册",null));
					return null;
				}				
			}
			
			if(StringUtil.isBlank(dto.getPassword())){
				super.printJSON(new JsonMsg(3, "密码不能为空",null));
				return null;
			}
			
			dto.setPassword(SHA.encryptPassword(dto.getPassword()));
			dto.setRegTime(new Date());
			dto.setRegIp(RequestUtil.getRemortIP(request));
			dto.setCreateTime(new Date());
			dto.setLoginCount(0);
			dto.setStatus("N");
			dto.setIsnew("Y");
			dto.setTerminal("PC");
			Integer id=userService.saveOrUpdate(dto);
			
			UserAccount account=new UserAccount();
			account.setUserId(dto.getId());
			account.setCreateTime(new Date());
			accountService.saveOrUpdate(account);
			
			if(id>0){
				super.printJSON(new JsonMsg(-1, "操作成功",null));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}
	
	/**
	 * 设置用户内部邀请码
	 * @param model
	 * @param userId 用户id
	 * @param insideInviteCode 内部邀请码
	 * @return
	 */
	@RequestMapping(value="/setUserInsideInviteCode",method=RequestMethod.POST)
	public String setUserInsideInviteCode(Model model,
									@RequestParam(value="userId") Integer userId,
									@RequestParam(value="insideInviteCode") String insideInviteCode)throws Exception{
		//TODO 手机号为邀请码时使用
		User user = userService.getById(userId);
		User parentUser = userService.getUserByPhone(insideInviteCode);
		if(user != null) {
			InviteRef ref = null;
			try {
				ref = userService.getInviteRefByUserId(userId);
			} catch (Exception e) {
				printJSON(new JsonMsg(0, "可能该用户存在多个邀请用户，请换一个用户再试。"));
				e.printStackTrace();
				return null;
			}
			if(ref != null) {
				printJSON(new JsonMsg(0, "您已存在邀请用户-userId:"+ref.getUserId()));
				return null;
			}
			if(parentUser == null) {
				printJSON(new JsonMsg(0, "邀请用户不存在,请填写正确的邀请码"));
				return null;
			}
			//建立邀请关系
			InviteRef inviteRef = new InviteRef();
			inviteRef.setUserId(userId);
			inviteRef.setPid(parentUser.getId());
			inviteRef.setTakeAward(0);
			inviteRef.setCreateTime(new Date());
			int item = userService.saveOrUpdateInviteRef(inviteRef);
			if(item>0) {
				printJSON(new JsonMsg(-1, "操作成功"));
			}else {
				printJSON(new JsonMsg(1, "操作失败"));
			}
		}
		/*if (user != null) {
			if (StringUtils.isNotBlank(insideInviteCode)) {
				List<User> userList=userService.getUserByInviteCode(insideInviteCode);
				if (userList.size()>0) {
					printJSON(new JsonMsg(1, "内部邀请码已存在，请重新输入！"));
					return null;
				}
			}
			user.setInsideInviteCode(insideInviteCode);
			Integer i = userService.saveOrUpdate(user);
			if (i > 0) {
				printJSON(new JsonMsg(-1, "操作成功"));
			}
		}*/
		return null;
	}
	
	
	@RequestMapping("/getByName")
	public String getByName(@RequestParam("username") String username){
		try {
			if(StringUtils.isBlank(username)){
				super.printJSON(new JsonMsg(1, "用户名不能为空",null));
			}
			User temp = frontUserService.selectByNameOrPhone(username);
			if(temp != null){
				super.printJSON(new JsonMsg(-1, "操作成功",temp));	
			}else{
				super.printJSON(new JsonMsg(2, "该用户名不存在",null));			
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}
	
	/**
	 * 删除用户
	 * @param id 用户id
	 * @return
	 */
	@RequestMapping("/delUser")
	public String delUser(Model model,@RequestParam Integer id){
		userService.deleteUser(id);
		return "redirect:/admin/user/list";
	}
	
	/**
	 *  
	 * @param id  邀请用户
	 * @param username 受邀用户名
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/ref")
	public String refUser(@RequestParam("id") Integer id,
						  @RequestParam("username") String username) throws Exception{
		if(StringUtils.isBlank(username)){
			super.printJSON(new JsonMsg(1, "邀请用户不能为空"));	
			return null;
		}
		User temp=new User();
		temp.setPhone(username);
		List<User> userList=userService.getByUser(temp);
		if(userList.size()==0){
			super.printJSON(new JsonMsg(1, "邀请用户不存在"));	
			return null;
		}else{
			Integer userId=userList.get(0).getId();
			InviteRef ref=frontUserService.getInviteRefByUserId(id);
			if(ref!=null){
				frontUserService.deleteInviteRef(ref.getId());
			}
			InviteRef newRef=new InviteRef();
			newRef.setTakeAward(0);
			newRef.setUserId(userId);
			newRef.setPid(id);
			newRef.setCreateTime(new Date());
			frontUserService.saveOrUpdateInviteRef(newRef);
			super.printJSON(new JsonMsg(-1, "操作成功"));	
			return null;
		}
	}
	
	/**
	 * 彻底删除用户
	 * @param userId 用户id
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/delete")
	public void deleteUser(Model model,@RequestParam Integer userId) throws Exception{
		try {
			bankCardService.deleteByUserId(userId);//删除用户的所有银行卡
			userAuthService.deleteByUserId(userId);//删除用户的所有认证信息
			accountService.deleteByUserId(userId);//删除用户账户
			userService.deleteUser(userId);//删除用户
			super.printJSON(new JsonMsg(-1, "删除用户成功！"));
		} catch (Exception e) {
			super.printJSON(new JsonMsg(1, "删除用户失败！"));
		}
	}
}
